package transport

import (
	"context"
	"rpcdemo/endpoint"
	"rpcdemo/pb"
	"rpcdemo/service"

	grpctransport "github.com/go-kit/kit/transport/grpc"
)

type TrimGRPCServer struct {
	pb.UnimplementedTrimSvcServer
	trim grpctransport.Handler
}

func NewTrimGRPCServer(svc service.TrimSvc) pb.TrimSvcServer {
	return &TrimGRPCServer{
		trim: grpctransport.NewServer(
			endpoint.MakeTrimSpaceEndpoint(svc),
			DecodeTrimRequest,
			EncodeTrimResponse,
		),
	}
}

func (s *TrimGRPCServer) TrimSpace(ctx context.Context, req *pb.TrimReq) (*pb.TrimResp, error) {
	_, res, err := s.trim.ServeGRPC(ctx, req)
	if err != nil {
		return nil, err
	}

	return res.(*pb.TrimResp), nil
}

func DecodeTrimRequest(_ context.Context, r interface{}) (interface{}, error) {
	req := r.(*pb.TrimReq)
	return endpoint.TrimSpaceRequest{S: req.Str}, nil
}

func EncodeTrimResponse(_ context.Context, r interface{}) (interface{}, error) {
	res := r.(endpoint.TrimSpaceResponse)
	return &pb.TrimResp{Str: res.S}, nil
}
